'use strict';

define(['../../controllers', '../service/errorService', 'datepicker'], function (controllers) {
    controllers.stat.register('ErrorController', ['$scope', 'ErrorService', function ($scope, errorService) {
        $scope.init = function() {
            $scope.query_optStartTime = '';
            $scope.query_optEndTime = '';
            $scope.pageNo = 1;
            $scope.pageSize = 10;

            $scope.collections = errorService.findCollections(function (collections) {
                $scope.collectionMap = {};
                for (var i = 0; i < collections.length; i++) {
                    $scope.collectionMap[collections[i].id] = collections[i];
                }
            });

            $('#query_errStartTime').datepicker({
                format: 'yyyy-mm-dd'
            }).on('changeDate', function (e) {
                var oldStartTime = $scope.query_errStartTime;
                var newStartTime = e.date.getDayBeginTime();
                if ($scope.query_errEndTime > 0 && newStartTime > $scope.query_errEndTime) {
                    $scope.query_errStartTime = oldStartTime > 0 ? oldStartTime : new Date($scope.query_errEndTime).getDayBeginTime();
                    $('#query_errStartTime').val(new Date($scope.query_errStartTime).format($scope.DATE_FORMAT));
                    return false;
                }
                $scope.query_errStartTime = newStartTime;
            });

            $('#query_errEndTime').datepicker({
                format: 'yyyy-mm-dd'
            }).on('changeDate', function (e) {
                var oldEndTime = $scope.query_errEndTime;
                var newEndTime = e.date.getDayEndTime();
                if ($scope.query_errStartTime> 0 && newEndTime < $scope.query_errStartTime) {
                    $scope.query_errEndTime = oldEndTime > 0 ? oldEndTime : new Date($scope.query_errStartTime).getDayEndTime();
                    $('#query_errEndTime').val(new Date($scope.query_errEndTime).format($scope.DATE_FORMAT));
                    return false;
                }
                $scope.query_errEndTime = newEndTime;
            });
        };
        $scope.query = function (pageNo) {
            if (pageNo != null) {
                $scope.pageNo = pageNo;
            }
            $scope.paged = errorService.query({
                collectionId: $scope.query_collectionId,
                errStartTime : $scope.query_errStartTime,
                errEndTime: $scope.query_errEndTime,
                pageNo: $scope.pageNo,
                pageSize: $scope.pageSize
            });
        };

        $scope.view = function(id) {
            errorService.get({id : id}, function(errorLog) {
                $scope.viewErrorLog = errorLog;
                $('#viewDialog').modal('show');
            });
        };
        $scope.init();
        $scope.query();
    }]);
});